# -*- coding: utf-8 -*-
import json
import os

from PIL import Image
import oss2

# https://help.aliyun.com/document_detail/32206.html
access_key_id = os.getenv('OSS_TEST_ACCESS_KEY_ID', 'LTAI5t6GSWck3LnmUDN8MWea')
access_key_secret = os.getenv('OSS_TEST_ACCESS_KEY_SECRET', 'jwQgdQBzIFI8IK94yXDXjrlA8nWJ6s')
bucket_name = os.getenv('OSS_TEST_BUCKET', 'math-maker')
endpoint = os.getenv('OSS_TEST_ENDPOINT', 'https://oss-cn-beijing.aliyuncs.com')

# 确认上面的参数都填写正确了
for param in (access_key_id, access_key_secret, bucket_name, endpoint):
  assert '<' not in param, '请设置参数：' + param
  
def get_bucket():
  return oss2.Bucket(oss2.Auth(access_key_id, access_key_secret), endpoint, bucket_name)

def get_image_info(image_file):
  """获取本地图片信息
  :param str image_file: 本地图片
  :return tuple: a 3-tuple(height, width, format).
  """
  im = Image.open(image_file)
  return im.height, im.width, im.format

def download_image(key, root =  'faces/', filename = None):
  bucket = get_bucket()
  """下载图片
  :param str key: 图片本地存储地址
  """

  if (filename == None):
    filename = root + key
  else:
    filename = root + filename
  
  # 判断是否存在图片
  if check_is_exist(filename) != True:
    directory = os.path.dirname(filename)
    mkdir(directory)
    bucket.get_object_to_file(key, filename)
    print(f"Successfully downloaded the image '{filename}'")
  
  return filename

def get_image_ext(image_path):
  """
  获取图片扩展名
  """
  filename, file_extension = os.path.splitext(image_path)
  return file_extension

def upload_image(key, file):
  bucket = get_bucket()
  result = bucket.put_object_from_file(key, file)

  # 验证是否上传成功，如果上传成功，打印HTTP状态码
  return result.status == 200

def check_is_exist(filename):
  return os.path.isfile(filename)

def mkdir(dir):
  print(dir, check_is_exist(dir))
  if check_is_exist(dir) == True:
    return
  
  try:
    os.makedirs(dir, exist_ok=True)
    print(f"Successfully created the directory '{dir}'")
  except OSError as error:
    print(f"Creation of the directory '{dir}' failed. Error: {error}")

def listOssDir(dir):
  bucket = get_bucket()
  # 列出Bucket中以prefix作为前缀的所有对象的文件名和最后修改时间(按页列出，每页最多100个条目)
  for obj in oss2.ObjectIterator(bucket, prefix=dir, delimiter='/'):
    if obj.is_prefix():  # 如果是目录，会以'/'结尾
        print("目录：", obj.key)
    else:  # 如果是文件
        print("文件：", obj.key)

# 上传示例图片
# bucket.put_object_from_file(key, 'example.jpg')

# 删除示例图片
# bucket.delete_object(key)
# 清除本地文件
# os.remove(new_pic)
